package com.tim.util;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * @Description: 运行脚本命令
 * @Version 1.0, 2021/5/14
 * @Author Tim
 */
public class CmdAndShUtil {

    public static void runBat(String... cmds) throws IOException, InterruptedException {
        if(cmds.length==0){
            return;
        }
        // 加final，防止错误赋值导致NPE
        final StringBuilder builder = new StringBuilder();
        for (String cmd : cmds) {
            if(StringUtils.isNotBlank(cmd)){
                // 移除首尾&&
                cmd = cmd.trim()
                        .replaceAll("^&&", "")
                        .replaceAll("&&$", "");
                if(StringUtils.isNotBlank(cmd)){
                    builder.append(cmd).append(" && ");
                }
            }
        }
        if(builder.length()!=0){

            runBatWithoutWindow(builder.toString());

        }
    }

    /**
     * 运行单个命令，多个时写脚本文件。pause，避免关闭窗口
     * cmd /c dir 是执行完dir命令后关闭命令窗口
     * cmd /k dir 是执行完dir命令后不关闭命令窗口
     * cmd /c start dir 会打开一个新窗口后执行dir命令，原窗口会关闭
     * cmd /k start dir 会打开一个新窗口后执行dir命令，原窗口不会关闭
     * 采用String参数，Runtime执行时会切分为数组，自行切分有问题。
     * shell命令不可执行，环境变量未设置。安装cygwin
     * */
    public static void runBatInWindow(String cmdStr) throws IOException {
        cmdStr = cmdStr.trim()
                .replaceAll("^&&", "")
                .replaceAll("&&$", "");
        cmdStr = "cmd.exe /k start "+cmdStr;
        Runtime.getRuntime().exec(cmdStr);
    }
    public static void runBatWithoutWindow(String cmdStr) throws IOException, InterruptedException {
        cmdStr = cmdStr.trim()
                .replaceAll("^&&", "")
                .replaceAll("&&$", "");
        cmdStr = "cmd.exe /c "+cmdStr;
        Process process = Runtime.getRuntime().exec(cmdStr);
        IOPrintUtil.printInputStream(process.getInputStream());
    }

    public static void runShell(){
        
    }

    /**   
     *@describe string执行，报错
     *@author chwm
     *@company 星球秀场
     *@create 2021/5/18 11:50
     */       
    public static void main(String[] args) throws Exception {
    //        runBat("echo AAAAAAAAAA");
//        runBatWithoutWindow(
//        "telnet localhost 2281 && "
//            + "invoke com.xqxc.api.plat.marketing.mis.test.TestMarketingMisService.getOk()\n");
        runBatInWindow("echo AAAAAAAAAA");
//        Runtime.getRuntime().exec("/bin/sh -c ls");

    }


}
